<template>
  <el-dialog :append-to-body="true" :close-on-click-modal="false" :before-close="cancel" :visible.sync="dialog" :title="isAdd ? '新增' : '编辑'" width="500px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
      <el-form-item label="广告图" >
        <el-upload
          :on-remove="handleRemove"
          :limit="1"
          :on-exceed="handleExceed"
          :before-upload="fileName"
          :on-success="handleAvatarSuccess"
          :data="token"
          :file-list="fileList"
          class="upload-demo"
          action="http://upload-z2.qiniup.com"
          list-type="picture-card">
          <i class="el-icon-plus"></i>
          <div slot="tip" class="el-upload__tip">建议上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </el-form-item>
      <el-form-item label="商户ID" >
        <el-input v-model="form.shopid" style="width: 370px;"/>
      </el-form-item>
      <el-form-item label="地区范围" >
        <el-cascader
          v-model="areaValue"
          :options="areaOptions"
          :props="areaprops"
          :key = "cascaderKey"
          clearable
          filterable
          style="width: 370px;"
          @change="areaChange"></el-cascader>
      </el-form-item>
      <el-form-item label="状态" >
        <el-switch
          v-model="form.status"
          :active-value="0"
          :inactive-value="1"
          active-color="#409EFF"
          inactive-color="#F56C6C"/>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit, postRequest } from '@/api/advertisement'
import axios from 'axios'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false, dialog: false,
      form: {
        id: '',
        url: '',
        province: '',
        city: '',
        region: '',
        jsondata: '',
        shopid: '',
        status: ''
      },
      rules: {},
      token: {}, fileList: [],
      areaValue: [], areaprops: { multiple: true }, cascaderKey: 1,
      areaOptions: []
    }
  },
  computed: {

  },
  methods: {
    getareaList() {
      axios.get('/static/area.json').then((res) => {
        ++this.cascaderKey
        const area = res.data
        this.areaOptions = this.filterTree(area)
      })
    },
    filterTree(tree) {
      const result = []
      tree.forEach((item) => {
        const value = item.name
        const label = item.name
        let children = item.children
        // 如果有子节点，递归
        if (children) {
          children = this.filterTree(children)
        }
        result.push({
          value,
          label,
          children
        })
      })
      return result
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.shopid == null && this.form.shopid === '' || this.form.jsondata == null && this.form.jsondata === '') {
            this.$message({
              message: '商店ID或地区范围必须填写一个',
              type: 'warning'
            })
          } else {
            this.loading = true
            if (this.isAdd) {
              this.doAdd()
            } else this.doEdit()
          }
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        // this.$parent.init()
        this.$parent.initMethod()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        // this.$parent.init()
        this.$parent.initMethod()
      }).catch(err => {
        this.loading = false
        console.log(err.response.data.message)
      })
    },
    resetForm() {
      this.dialog = false
      this.$refs['form'].resetFields()
      this.form = {
        url: '',
        province: '',
        city: '',
        region: '',
        jsondata: '',
        shopid: '',
        status: 0
      }
      this.areaValue = []
      this.fileList = []
    },

    getToke() {
      postRequest('/order/token').then(resp => {
        this.token = resp.data
      })
    },
    // 上传图片的操作
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.form.url = ''
      this.fileList = []
    },
    handleAvatarSuccess(res, file) {
      // this.url = URL.createObjectURL(file.raw)
      this.form.url = 'http://file.xustan.com/' + res.key
      postRequest('/order/token').then(resp => {
        this.token = resp.data
      })
    },
    fileName(file) {
      this.token.key = file.lastModified + '-' + file.name
    },

    areaChange(val) {
      console.log(val)
      const province = []; const city = []; const region = []; let data = ''
      val.forEach(function(item) {
        province.push(item[0])
        city.push(item[1])
        region.push(item[2])
        data += item.join('-') + '#'
      })
      this.form.province = province.filter(function(item, index, self) { return self.indexOf(item) === index }).join('-')
      this.form.city = city.filter(function(item, index, self) { return self.indexOf(item) === index }).join('-')
      this.form.region = region.join('-')
      this.form.jsondata = data
    }

  }
}
</script>

<style scoped>
  .avatar {
    width: 100%;
    height: 100%;
    display: block;
    object-fit: scale-down;
  }
</style>
